package cn.jinjimi.app.search;


import android.os.Handler;
import android.os.Message;

import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.entity.Company;

import java.util.List;


/**
 * 查询
 * <p>
 * <p>
 * Created by jinsen on 15/12/7.
 */
public class CompanySearchProxy {

    //当前需要查询的关键字
    private String mCurKeyWords = null;

    public CompanySearchProxy(SearchResultListener listener, List<Company> list) {
        mCompanyProvier = new CompanyProvider(listener, list);
    }

    /**
     * 提交查询关键字
     *
     * @param keywords
     */
    public void query(String keywords) {
        //等待时间
        long DELAY_TIME = 400;
        int MSG_QUERY_CODE = 0x0;

        mStartQueryHandler.removeMessages(MSG_QUERY_CODE);
        cancelQuery();

        if (StringUtils.isEmpty(keywords)) {
            mCompanyProvier.sendEmptyCallback();
            return;
        }

        mCurKeyWords = keywords;
        mStartQueryHandler.sendEmptyMessageDelayed(MSG_QUERY_CODE, DELAY_TIME);
    }

    /**
     * 开始执行查询
     */
    private void doQuery() {
        mCompanyProvier.query(mCurKeyWords);
    }

    /**
     * 取消查询
     */
    public void cancelQuery() {
        mCompanyProvier.cancelQuery();
    }

    public void destory() {
        mCompanyProvier.cancelQuery();
        mCompanyProvier = null;
    }

    Handler mStartQueryHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            doQuery();
        }
    };


    CompanyProvider mCompanyProvier;
}
